//
//  UIScrollView+IndexPath.m
//  YHSuoShi
//
//  Created by 林宁宁 on 2021/1/14.
//  Copyright © 2021 林宁宁. All rights reserved.
//

#import "UIScrollView+IndexPath.h"
#import <objc/runtime.h>

@implementation UIScrollView (IndexPath)


-(void (^)(UIScrollView * _Nonnull))scrollingBlock{
    return objc_getAssociatedObject(self, @selector(scrollingBlock));
}
-(void)setScrollingBlock:(void (^)(UIScrollView * _Nonnull))scrollingBlock{
    objc_setAssociatedObject(self, @selector(scrollingBlock), scrollingBlock, OBJC_ASSOCIATION_COPY);
}

-(void (^)(UIScrollView * _Nonnull))scrollEndBlock{
    return objc_getAssociatedObject(self, @selector(scrollEndBlock));
}
-(void)setScrollEndBlock:(void (^)(UIScrollView * _Nonnull))scrollEndBlock{
    objc_setAssociatedObject(self, @selector(scrollEndBlock), scrollEndBlock, OBJC_ASSOCIATION_COPY);
}

- (void)yh_scrollViewDidScroll:(UIScrollView *)scrollView{
    if(![self yh_isTableCollectionView]){
        return;
    }
    
    if(self.scrollingBlock){
        self.scrollingBlock(scrollView);
    }
}

- (void)yh_scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    // 停止类型1、停止类型2
    BOOL scrollToScrollStop = !scrollView.tracking && !scrollView.dragging && !scrollView.decelerating;
    if (scrollToScrollStop) {
        [self scrollViewDidEndScroll];
    }
}
- (void)yh_scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if (!decelerate) {
        // 停止类型3
        BOOL dragToDragStop = scrollView.tracking && !scrollView.dragging && !scrollView.decelerating;
        if (dragToDragStop) {
            [self scrollViewDidEndScroll];
        }
    }
}

- (void)yh_scrollViewDidEndAnimation:(UIScrollView *)scrollView{
    [self yh_scrollViewDidEndDecelerating:scrollView];
}


- (void)scrollViewDidEndScroll {
    if(![self yh_isTableCollectionView]){
        return;
    }
    if(self.scrollEndBlock){
        self.scrollEndBlock(self);
    }
}

- (BOOL)yh_isTableCollectionView{
    if([self isKindOfClass:[UITableView class]]){
        return YES;
    }else if ([self isKindOfClass:[UICollectionView class]]){
        return YES;
    }else{
        return NO;
    }
}


- (CGRect)yh_getRectForRowAtIndexpath:(NSIndexPath *)indexPath{
    if([self isKindOfClass:[UITableView class]]){
        UITableView * tableV = (UITableView *)self;
        CGRect playingRect = [tableV rectForRowAtIndexPath:indexPath];
        return playingRect;
    }else if ([self isKindOfClass:[UICollectionView class]]){
        UICollectionView * collectV = (UICollectionView *)self;
        
        UICollectionViewLayoutAttributes * atttibute = [collectV.collectionViewLayout layoutAttributesForItemAtIndexPath:indexPath];
        CGRect frame = atttibute.frame;
        if([collectV.collectionViewLayout isKindOfClass:[UICollectionViewFlowLayout class]]){
            UICollectionViewFlowLayout * flowLayout = (UICollectionViewFlowLayout *)collectV.collectionViewLayout;
            if(CGRectEqualToRect(frame, CGRectZero)){
                frame.size = flowLayout.itemSize;
            }
            frame.size.height = frame.size.height + flowLayout.minimumLineSpacing;
            frame.origin.y = frame.origin.y - flowLayout.minimumLineSpacing*0.5;
        }
        return frame;
    }else{
        return CGRectZero;
    }
}

- (NSArray *)currentVisibleRows{
    NSArray * indexPatchs = @[];
    if([self isKindOfClass:[UITableView class]]){
        UITableView * tableV = (UITableView *)self;
        indexPatchs = tableV.indexPathsForVisibleRows;
    }else if ([self isKindOfClass:[UICollectionView class]]){
        UICollectionView * collectV = (UICollectionView *)self;
        indexPatchs = collectV.indexPathsForVisibleItems;
    }else{
        return @[];
    }
    indexPatchs = [indexPatchs sortedArrayUsingSelector:@selector(compare:)];
    return indexPatchs;
}

- (NSIndexPath *)firstIndexPath{
    return [self currentVisibleRows].firstObject;
}

- (NSIndexPath *)screenCenterIndexPath{
    CGPoint point = CGPointMake(CGRectGetMidX(self.superview.bounds), CGRectGetMinY(self.superview.bounds));
    return [self indexPathAtPoint:point];
}
- (NSIndexPath *)screenTopIndexPath{
    CGPoint point = CGPointMake(CGRectGetMidX(self.superview.bounds), CGRectGetMidY(self.superview.bounds));
    return [self indexPathAtPoint:point];
}
- (NSIndexPath *)screenLeftIndexPath{
    CGPoint point = CGPointMake(0, CGRectGetMidY(self.superview.bounds));
    return [self indexPathAtPoint:point];
}
- (NSIndexPath *)screenBottomIndexPath{
    CGPoint point = CGPointMake(CGRectGetMidX(self.superview.bounds), CGRectGetMaxY(self.superview.bounds));
    return [self indexPathAtPoint:point];
}

- (NSIndexPath *)indexPathAtPoint:(CGPoint)point{
    NSArray * indexPatchs = @[];
    BOOL isVertical = YES;
    
    if([self isKindOfClass:[UITableView class]]){
        UITableView * tableV = (UITableView *)self;
        indexPatchs = tableV.indexPathsForVisibleRows;
    }else if ([self isKindOfClass:[UICollectionView class]]){
        UICollectionView * collectV = (UICollectionView *)self;
        indexPatchs = collectV.indexPathsForVisibleItems;
        if([collectV.collectionViewLayout isKindOfClass:[UICollectionViewFlowLayout class]]){
            UICollectionViewFlowLayout * layout = (UICollectionViewFlowLayout *)collectV.collectionViewLayout;
            isVertical = (layout.scrollDirection == UICollectionViewScrollDirectionVertical);
        }
    }else{
        return nil;
    }
    if(indexPatchs.count == 0){
        return nil;
    }

    CGFloat height = self.frame.size.height;
    CGFloat contentOffsetY;
    CGFloat bottomOffset;
    
    if(isVertical){
        contentOffsetY = self.contentOffset.y;
        bottomOffset = self.contentSize.height - contentOffsetY;
    }else{
        contentOffsetY = self.contentOffset.x;
        bottomOffset = self.contentSize.width - contentOffsetY;
    }
    
    if (bottomOffset <= height){
        //滚到最底部的时候 取最后一个
        indexPatchs = [indexPatchs sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"section" ascending:YES],[NSSortDescriptor sortDescriptorWithKey:@"row" ascending:YES]]];
        NSIndexPath * lastIndexP = indexPatchs.lastObject;
        return lastIndexP;
    }else if (contentOffsetY <= 0){
        //表格在顶部的时候 播放第一个
        indexPatchs = [indexPatchs sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"section" ascending:YES],[NSSortDescriptor sortDescriptorWithKey:@"row" ascending:YES]]];
        NSIndexPath * firstIndexP = indexPatchs.firstObject;
        return firstIndexP;
    }
        
    for(NSIndexPath * item in indexPatchs){
        CGRect playingRect = [self yh_getRectForRowAtIndexpath:item];
        CGRect rectInSuperview = [self convertRect:playingRect toView:self.superview];
        if(CGRectContainsPoint(rectInSuperview, point)){
            return item;
        }
    }
    return nil;
}

@end
